from flask import Flask, request, jsonify
import json
import redis
from datetime import datetime
import logging
from logger_config import logger

app = Flask(__name__)

# 初始化 Redis 连接
redis_client = redis.Redis(host='127.0.0.1', port=6379, db=0)

def get_target_users(message_data):
    """获取消息的目标用户
    Args:
        message_data: 消息数据
    Returns:
        list: 目标用户列表
    """
    try:
        if not message_data.get('Data'):
            return None  
        message = message_data.get('Data')
        to_user = message.get("ToUserName", {}).get("string", "")
        # create_time = message.get("CreateTime", 0)
        return to_user
    except Exception as e:
        logger.error(f"获取目标用户时出错: {str(e)}")
        return []

@app.route('/msg2mq', methods=['POST'])
def msg2mq():
    """接收消息并推送到 Redis
    消息格式：
    {
        "Data": {
            "MsgType": 1,
            "FromUserName": {"string": "wxid_xxx"},
            "Content": {"string": "message content"}
        }
    }
    """
    try:
        message_data = request.get_json()
        if not message_data:
            return jsonify({"status": "error", "error": "missing data"})
            
        # 获取目标用户
        target_user = get_target_users(message_data)
        if not target_user:
            return jsonify({"status": "ignored", "reason": "no target users"})
            
        # 记录日志
        logger.info("\n" + "="*50)
        logger.info(f"收到新消息: {datetime.now()}")
        logger.info("-"*50)
        logger.info(f"目标用户: {target_user}")
        logger.info(json.dumps(message_data, ensure_ascii=False, indent=2))
        logger.info("="*50)
        
        # 推送消息到每个目标用户的频道
        message_json = json.dumps(message_data, ensure_ascii=False)
        redis_client.publish(target_user, message_json)    
    except Exception as e:
        logger.error(f"处理消息时出错: {str(e)}")
        return jsonify({"status": "error", "error": str(e)})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3080)
